<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    :footer="false"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-form-model ref="form" :model="model" :rules="validatorRules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="入库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="documentDate">
            <j-date v-model="model.documentDate" date-format="YYYY-MM-DD"></j-date>
          </a-form-model-item>
        </a-col>
        <!--        <a-col :span='12'>-->
        <!--          <a-form-model-item label='日期序列' :labelCol='labelCol' :wrapperCol='wrapperCol' prop='deliveryDate'>-->
        <!--            <a-select v-model='model.deliveryDate'>-->
        <!--              <a-select-option v-for="d in dateList" :key="d.value">-->
        <!--                {{ d.title }}-->
        <!--              </a-select-option>-->
        <!--            </a-select>-->
        <!--          </a-form-model-item>-->
        <!--        </a-col>-->
      </a-row>
    </a-form-model>

    <a-button v-if="!editable" type="primary" @click="handleEditNumber" style="margin-bottom: 10px;margin-top: -10px;"
      >编辑全部
    </a-button>
    <a-button v-else type="primary" @click="handleSaveNumber" style="margin-bottom: 10px;margin-top: -10px;"
      >保存全部
    </a-button>
    <a-table
      ref="table"
      size="small"
      bordered
      rowKey="id"
      style="padding: 1px"
      :scroll="{ x: true }"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="false"
      :loading="loading"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      @change="handleTableChange"
    >
      <template slot="action" slot-scope="text, record">
        <div class="editable-row-operations" v-show="record.status !== 1">
          <span v-if="record.editable">
            <a @click="() => save(record)">保存</a>
            <a-divider type="vertical" style="background-color: grey"></a-divider>
            <a @click="() => cancel(record)">取消</a>
          </span>
          <span v-else>
            <a :disabled="editable" @click="edit(record)">编辑</a>
          </span>
        </div>
      </template>

      <template slot="number" slot-scope="text, record">
        <a-input-number
          v-if="record.editable || editable"
          @change="handleNumberChange($event, record)"
          :min="0"
          style="width: 80px"
        />
        <span v-else>{{ record.number }}</span>
      </template>
      <template slot="totalNumber" slot-scope="text, record">
        <a-tooltip>
          <a-input-number
            v-if="record.editable || editable"
            v-model:value="record.totalNumber"
            :min="0"
            :max="record.maxNumber"
            style="width: 80px"
          />
          <span v-else>{{ record.totalNumber }}</span>
          <template slot="title">剩余交货总数为{{ record.maxNumber }}</template>
        </a-tooltip>
      </template>
      <template slot="warehouse" slot-scope="text, record">
        <j-dict-select-tag
          v-if="record.editable || editable"
          v-model="record.warehouse"
          dict-code="hf_warehouse,warehouse_name,id"
          style=""
        />
        <span v-else>{{ record.warehouse_dictText }}</span>
      </template>
    </a-table>
    <a-button
      type="primary"
      :loading="confirmLoading"
      @click="generatePurchaseIn"
      style="margin-left: calc(100% - 130px);margin-top: 10px"
      >生成采购入库单
    </a-button>
  </a-modal>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { postAction } from '@api/manage'
import dayjs from 'dayjs'

export default {
  name: 'GeneratePurchaseInputModal',
  mixins: [JeecgListMixin],
  props: ['supplierId', 'supplierOrderSerial', 'sourceId', 'sourceSerial'],
  data() {
    return {
      title: '生成销售出库单',
      width: 1200,
      visible: false,
      queryParam: {},
      editable: false,
      disableMixinCreated: true,
      editingKey: '',
      model: {
        documentDate: dayjs().format('YYYY-MM-DD')
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 10 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 }
      },
      /* table加载状态 */
      loading: false,
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode'
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType_dictText'
        },
        {
          title: '总数',
          align: 'center',
          dataIndex: 'totalNumber',
          scopedSlots: { customRender: 'totalNumber' }
        },
        {
          title: '出货仓库',
          align: 'center',
          dataIndex: 'warehouse_dictText',
          scopedSlots: { customRender: 'warehouse' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],

      confirmLoading: false,
      validatorRules: {
        deliveryDate: [{ required: true, message: '请选择日期序列!' }],
        documentDate: [{ required: true, message: '请选择日期!' }]
      },
      url: {
        generatePurchaseIn: '/purchase/hfPurchaseInput/generatePurchaseIn'
      },
      saleOrderIds: '',
      numberSlots: [],
      saleOutSlots: [],
      dateList: []
    }
  },
  methods: {
    save(record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.materialCode === record.materialCode)
      target.editable = false
      this.dataSource = newData
      this.selectValue = ''
    },
    cancel(record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.materialCode === record.materialCode)
      if (target) {
        target.editable = false
        this.dataSource = newData
        this.selectValue = ''
      }
    },
    edit(record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.materialCode === record.materialCode)
      if (target) {
        target.editable = true
        this.selectValue = target.productCode
        this.dataSource = newData
      }
    },
    clearList() {
      this.dataSource = []
      this.selectedRowKeys = []
      this.ipagination.current = 1
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    handleEditNumber() {
      this.editable = true
    },
    handleSaveNumber() {
      this.editable = false
    },
    handleNumberChange(value, record) {
      record.number = value
      record.totalNumber = value * record.perNumber
    },
    loadData(data) {
      this.dataSource = data.map(item => ({ ...item, totalNumber: 0, number: 0 }))
    },
    generatePurchaseIn() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          let params = {
            supplierId: this.supplierId,
            supplierOrderSerial: this.supplierOrderSerial,
            sourceId: this.sourceId,
            sourceSerial: this.sourceSerial,
            documentDate: this.model.documentDate,
            hfPurchaseDetailList: this.dataSource
          }

          postAction(this.url.generatePurchaseIn, params)
            .then(res => {
              if (res.success) {
                this.$message.success('生成成功')
                this.$emit('refresh')
                this.close()
              }
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    }
  }
}
</script>

<style scoped></style>
